package list;

/**
 * 多个线程操作同一个变量就会有线程安全问题,即使加上volatile也不行
 */
public class Helllo {

    public static void main(String[] args) throws Exception{
        Holder holder = new Holder();
        holder.hello();

        Thread t1 = new Thread(() -> {
            for(int i = 0; i<1000;i++){
                holder.i++;
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for(int i = 0; i<1000;i++){
                holder.i++;
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread t3 = new Thread(() -> {
            for(int i = 0; i<1000;i++){
                holder.i++;
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t4 = new Thread(() -> {
            for(int i = 0; i<1000;i++){
                holder.i++;
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t5 = new Thread(() -> {
            for(int i = 0; i<1000;i++){
                holder.i++;
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        t5.join();
        System.out.println(holder.i);

    }




}

class Holder{
    volatile int i = 0;

    protected void hello(){

    }
}
